/**
 * 聊天记录管理页面功能
 */

// 全局变量
let chatList = [];
let currentChatId = null;
let isLoading = false;
let currentFilter = 'all';
let searchTerm = '';
let isWechatLoggedIn = false;
let debugMode = true; // 启用调试模式

// 确保window.chatList全局变量存在
window.chatList = window.chatList || [];

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('初始化聊天管理页面');
    
    // 确保chatList是数组
    if (!Array.isArray(window.chatList)) {
        console.error('window.chatList不是数组，重置为空数组');
        window.chatList = [];
    }
    
    // 同步全局变量和局部变量
    chatList = window.chatList;
    
    // 检查微信登录状态
    checkWechatLoginStatus();
    
    // 初始化加载聊天列表
    loadChatList();
    
    // 初始化加载聊天统计
    loadChatStatistics();
    
    // 绑定筛选按钮事件
    document.getElementById('filterAll')?.addEventListener('click', () => filterChats('all'));
    document.getElementById('filterGroups')?.addEventListener('click', () => filterChats('group'));
    document.getElementById('filterPrivate')?.addEventListener('click', () => filterChats('private'));
    
    // 绑定搜索框事件
    const searchInput = document.getElementById('chatSearchInput');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            searchTerm = this.value.toLowerCase();
            applyFilters();
        });
    }
    
    // 设置自动刷新 (每60秒)
    setInterval(() => {
        if (!isLoading) {
            checkWechatLoginStatus();
            loadChatStatistics();
            // 只有在查看列表时才自动刷新列表
            if (!currentChatId) {
                loadChatList(false); // 静默刷新
            }
        }
    }, 60000);
    
    // 添加点击事件处理
    document.addEventListener('click', function(event) {
        // 查找最近的聊天项
        const chatItem = event.target.closest('.chat-item');
        if (chatItem && !event.target.closest('button')) {
            const chatId = chatItem.dataset.chatId;
            if (chatId) {
                viewChatDetail(chatId);
            }
        }
    });
});

// 调试日志函数
function debugLog(message, data) {
    if (!debugMode) return;
    
    if (data) {
        console.log(`[DEBUG] ${message}`, data);
    } else {
        console.log(`[DEBUG] ${message}`);
    }
}

/**
 * 检查微信登录状态
 */
function checkWechatLoginStatus() {
    fetch('/api/wechat/status')
        .then(response => response.json())
        .then(data => {
            if (data && data.success) {
                isWechatLoggedIn = data.data && data.data.is_logged_in;
                
                // 显示或隐藏登录提示
                const loginAlert = document.getElementById('loginStatusAlert');
                if (loginAlert) {
                    loginAlert.style.display = isWechatLoggedIn ? 'none' : 'block';
                }
            }
        })
        .catch(error => {
            console.error('检查微信登录状态失败:', error);
            isWechatLoggedIn = false;
        });
}

/**
 * 加载聊天列表
 * @param {boolean} showLoader 是否显示加载指示器
 */
function loadChatList(showLoader = true) {
    if (isLoading) {
        return;
    }
    
    isLoading = true;
    const chatListContainer = document.getElementById('chatListContainer');
    const errorContainer = document.getElementById('chatListError');
    
    if (!chatListContainer) {
        console.error('找不到聊天列表容器元素');
        isLoading = false;
        return;
    }
    
    if (showLoader) {
        chatListContainer.innerHTML = `
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-3 text-muted">加载中...</p>
            </div>`;
    }
    
    // 清除错误信息
    if (errorContainer) {
        errorContainer.style.display = 'none';
    }
    
    fetch('/api/chat/list')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data && data.success && Array.isArray(data.data)) {
                chatList = data.data;
                renderChatList();
            } else {
                throw new Error(data?.message || '数据格式错误');
            }
        })
        .catch(error => {
            console.error('加载聊天列表失败:', error);
            
            if (errorContainer) {
                errorContainer.textContent = `加载聊天列表失败: ${error.message}`;
                errorContainer.style.display = 'block';
            }
            
            chatListContainer.innerHTML = `
                <div class="empty-state">
                    <i class="bi bi-exclamation-circle"></i>
                    <p>加载聊天列表失败</p>
                    <button class="btn btn-primary btn-sm" onclick="refreshChatList()">
                        <i class="bi bi-arrow-clockwise me-1"></i>重试
                    </button>
                </div>`;
        })
        .finally(() => {
            isLoading = false;
        });
}

/**
 * 渲染聊天列表
 */
function renderChatList() {
    const container = document.getElementById('chatListContainer');
    if (!container) return;
    
    if (!Array.isArray(chatList) || chatList.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-chat-square"></i>
                <p>暂无聊天记录</p>
            </div>`;
        return;
    }
    
    // 过滤聊天列表
    const filteredChats = chatList.filter(chat => {
        // 应用类型筛选
        if (currentFilter !== 'all') {
            if (currentFilter === 'group' && chat.chat_type !== 'group') return false;
            if (currentFilter === 'private' && chat.chat_type !== 'private') return false;
        }
        
        // 应用搜索筛选
        if (searchTerm && searchTerm.length > 0) {
            const chatName = (chat.chat_name || '').toLowerCase();
            const lastMessage = (chat.last_message || '').toLowerCase();
            return chatName.includes(searchTerm) || lastMessage.includes(searchTerm);
        }
        
        return true;
    });
    
    if (filteredChats.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-search"></i>
                <p>没有找到匹配的聊天</p>
                <button class="btn btn-outline-secondary btn-sm" onclick="resetFilters()">
                    <i class="bi bi-x-circle me-1"></i>清除筛选
                </button>
            </div>`;
        return;
    }
    
    // 渲染聊天列表
    let html = '';
    
    filteredChats.forEach(chat => {
        const chatName = chat.chat_name || chat.chat_id || '未命名聊天';
        const lastMessage = chat.last_message || '暂无消息';
        const lastTime = chat.last_time ? formatTime(chat.last_time) : '';
        const isGroup = chat.chat_type === 'group';
        
        // 获取头像或初始字母
        let avatarContent = '';
        if (chat.avatar && chat.avatar !== '') {
            avatarContent = `<img src="${chat.avatar}" alt="${chatName}" class="w-100 h-100 rounded-circle">`;
        } else {
            const initial = chatName.charAt(0).toUpperCase();
            avatarContent = initial;
        }
        
        // 消息数量徽章
        const badgeHtml = chat.message_count > 0 ? 
            `<span class="chat-badge">${chat.message_count > 99 ? '99+' : chat.message_count}</span>` : '';
        
        html += `
            <div class="chat-item d-flex align-items-center ${currentChatId === chat.chat_id ? 'active' : ''}" 
                 data-chat-id="${chat.chat_id}" onclick="viewChatDetail('${chat.chat_id}')">
                <div class="chat-avatar ${isGroup ? 'group' : 'private'} flex-shrink-0">
                    ${avatarContent}
                </div>
                <div class="ms-3 flex-grow-1 overflow-hidden">
                    <div class="d-flex justify-content-between">
                        <div class="chat-name">${escapeHtml(chatName)}</div>
                        <small class="chat-time text-nowrap ms-2">${lastTime}</small>
                    </div>
                    <div class="chat-message">${escapeHtml(lastMessage)}</div>
                </div>
                ${badgeHtml}
            </div>`;
    });
    
    container.innerHTML = html;
}

/**
 * 加载聊天统计
 */
function loadChatStatistics() {
    fetch('/api/chat/statistics')
        .then(response => response.json())
        .then(data => {
            if (data && data.success && data.data) {
                const stats = data.data;
                
                // 更新统计数字
                document.getElementById('totalMessages').textContent = stats.total_messages || 0;
                document.getElementById('groupMessages').textContent = stats.group_messages || 0;
                document.getElementById('privateMessages').textContent = stats.private_messages || 0;
                document.getElementById('todayMessages').textContent = stats.today_messages || 0;
                
                // 动画效果
                document.querySelectorAll('.card').forEach(card => {
                    card.classList.add('animate__animated', 'animate__fadeIn');
                });
            }
        })
        .catch(error => {
            console.error('加载统计信息失败:', error);
        });
}

/**
 * 查看聊天详情
 * @param {string} chatId 聊天ID
 */
function viewChatDetail(chatId) {
    if (isLoading || !chatId) return;
    
    currentChatId = chatId;
    isLoading = true;
    
    // 切换视图（在移动端尤其重要）
    const chatDetailPanel = document.getElementById('chatDetailPanel');
    const backButton = document.getElementById('backButton');
    const refreshDetailButton = document.getElementById('refreshDetailButton');
    
    // 在移动视图中，隐藏聊天列表面板
    if (window.innerWidth < 768) {
        document.getElementById('chatListPanel').classList.add('d-none');
    }
    
    // 显示返回按钮和刷新按钮
    backButton.style.display = 'inline-block';
    refreshDetailButton.style.display = 'inline-block';
    chatDetailPanel.classList.remove('d-none');
    
    // 高亮选中的聊天
    document.querySelectorAll('.chat-item').forEach(item => {
        if (item.dataset.chatId === chatId) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
    
    const chatDetailContainer = document.getElementById('chatDetailContainer');
    if (chatDetailContainer) {
        chatDetailContainer.innerHTML = `
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-3 text-muted">加载聊天记录中...</p>
            </div>`;
        
        fetch(`/api/chat/detail/${encodeURIComponent(chatId)}`)
            .then(response => response.json())
            .then(data => {
                if (data && data.success && data.data) {
                    const chatInfo = data.data.chat_info || {};
                    const messages = data.data.messages || [];
                    
                    // 设置聊天标题
                    const chatDetailTitle = document.getElementById('chatDetailTitle');
                    if (chatDetailTitle) {
                        const chatName = chatInfo.chat_name || chatId;
                        const chatTypeIcon = chatInfo.chat_type === 'group' ? 
                            '<i class="bi bi-people-fill me-2 text-success"></i>' : 
                            '<i class="bi bi-person-fill me-2 text-primary"></i>';
                        
                        chatDetailTitle.innerHTML = `${chatTypeIcon}${escapeHtml(chatName)}`;
                        if (chatInfo.chat_type === 'group' && chatInfo.member_count) {
                            chatDetailTitle.innerHTML += ` <small class="text-muted">(${chatInfo.member_count}人)</small>`;
                        }
                    }
                    
                    renderChatDetail(chatId, messages);
                } else {
                    throw new Error(data?.message || '获取聊天详情失败');
                }
            })
            .catch(error => {
                console.error('加载聊天详情失败:', error);
                chatDetailContainer.innerHTML = `
                    <div class="empty-state">
                        <i class="bi bi-exclamation-circle"></i>
                        <p>加载聊天详情失败: ${error.message}</p>
                        <button class="btn btn-primary btn-sm" onclick="viewChatDetail('${chatId}')">
                            <i class="bi bi-arrow-clockwise me-1"></i>重试
                        </button>
                    </div>`;
            })
            .finally(() => {
                isLoading = false;
            });
    }
}

/**
 * 渲染聊天详情
 * @param {string} chatId 聊天ID
 * @param {Array} messages 消息列表
 */
function renderChatDetail(chatId, messages) {
    const container = document.getElementById('chatDetailContainer');
    if (!container) return;
    
    if (!Array.isArray(messages) || messages.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-chat-square-text"></i>
                <p>暂无消息记录</p>
            </div>`;
        return;
    }
    
    let html = '';
    const selfWxid = ''; // 如果有自己的wxid可以在这里设置
    
    // 按照时间顺序显示消息（最新的在下面）
    messages.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
    
    messages.forEach(msg => {
        const isSelf = selfWxid && msg.sender_wxid === selfWxid;
        const bubbleClass = isSelf ? 'sent' : 'received';
        const alignment = isSelf ? 'text-end' : '';
        const timestamp = msg.timestamp ? formatTime(msg.timestamp, true) : '';
        
        // 根据消息类型处理不同的内容
        let contentHtml = '';
        switch (Number(msg.msg_type)) {
            case 1: // 文本消息
                contentHtml = `<div class="message-text">${escapeHtml(msg.content)}</div>`;
                break;
            case 3: // 图片消息
                contentHtml = `
                    <div class="message-image">
                        <i class="bi bi-image me-1"></i>
                        <span>[图片消息]</span>
                    </div>`;
                break;
            case 34: // 语音消息
                contentHtml = `
                    <div class="message-voice">
                        <i class="bi bi-mic-fill"></i>
                        <span>[语音消息]</span>
                    </div>`;
                break;
            case 43: // 视频消息
                contentHtml = `
                    <div class="message-video">
                        <i class="bi bi-camera-video-fill"></i>
                        <span>[视频消息]</span>
                    </div>`;
                break;
            case 47: // 表情消息
                contentHtml = `
                    <div class="message-emoji">
                        <i class="bi bi-emoji-smile"></i>
                        <span>[表情消息]</span>
                    </div>`;
                break;
            case 49: // 文件消息
                contentHtml = `
                    <div class="message-file">
                        <i class="bi bi-file-earmark"></i>
                        <span>[文件消息]</span>
                    </div>`;
                break;
            default:
                contentHtml = `<div class="message-text">${escapeHtml(msg.content)}</div>`;
        }
        
        html += `
            <div class="${alignment}">
                <div class="message-bubble ${bubbleClass}">
                    ${msg.is_group && !isSelf ? `<div class="message-sender">${escapeHtml(msg.sender_nickname)}</div>` : ''}
                    <div class="message-content">
                        ${contentHtml}
                    </div>
                    <div class="message-time">${timestamp}</div>
                </div>
            </div>`;
    });
    
    container.innerHTML = html;
    
    // 滚动到底部
    container.scrollTop = container.scrollHeight;
}

/**
 * 返回聊天列表
 */
function backToChatList() {
    currentChatId = null;
    
    // 如果在移动视图中，显示聊天列表面板
    if (window.innerWidth < 768) {
        document.getElementById('chatListPanel').classList.remove('d-none');
    }
    
    // 隐藏返回按钮和刷新按钮
    document.getElementById('backButton').style.display = 'none';
    document.getElementById('refreshDetailButton').style.display = 'none';
    
    // 清除聊天项的高亮状态
    document.querySelectorAll('.chat-item').forEach(item => {
        item.classList.remove('active');
    });
    
    // 显示默认的聊天详情提示
    const chatDetailContainer = document.getElementById('chatDetailContainer');
    if (chatDetailContainer) {
        chatDetailContainer.innerHTML = `
            <div class="text-center py-5">
                <i class="bi bi-chat-square-text text-muted fs-1"></i>
                <p class="mt-3 text-muted">选择一个聊天查看详情</p>
            </div>`;
    }
}

/**
 * 刷新当前聊天详情
 */
function refreshCurrentChat() {
    if (currentChatId) {
        viewChatDetail(currentChatId);
    }
}

/**
 * 筛选聊天列表
 * @param {string} filter 筛选类型 'all', 'group', 'private'
 */
function filterChats(filter) {
    currentFilter = filter;
    
    // 更新按钮状态
    document.querySelectorAll('#filterAll, #filterGroups, #filterPrivate').forEach(btn => {
        btn.classList.remove('active');
    });
    
    switch (filter) {
        case 'group':
            document.getElementById('filterGroups').classList.add('active');
            break;
        case 'private':
            document.getElementById('filterPrivate').classList.add('active');
            break;
        default:
            document.getElementById('filterAll').classList.add('active');
    }
    
    applyFilters();
}

/**
 * 应用筛选并重新渲染列表
 */
function applyFilters() {
    renderChatList();
}

/**
 * 重置筛选条件
 */
function resetFilters() {
    currentFilter = 'all';
    searchTerm = '';
    
    // 重置搜索框
    const searchInput = document.getElementById('chatSearchInput');
    if (searchInput) {
        searchInput.value = '';
    }
    
    // 重置筛选按钮
    filterChats('all');
}

/**
 * 刷新聊天列表
 */
function refreshChatList() {
    loadChatList(true);
}

/**
 * 格式化时间
 * @param {string} isoTime ISO格式时间字符串
 * @param {boolean} withSeconds 是否包含秒数
 * @returns {string} 格式化后的时间
 */
function formatTime(isoTime, withSeconds = false) {
    try {
        const date = new Date(isoTime);
        if (isNaN(date.getTime())) {
            return '';
        }
        
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const yesterday = new Date(today);
        yesterday.setDate(yesterday.getDate() - 1);
        
        const isToday = date >= today;
        const isYesterday = date >= yesterday && date < today;
        
        if (isToday) {
            return withSeconds ? 
                date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) :
                date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        } else if (isYesterday) {
            return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        } else {
            return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
        }
    } catch (e) {
        return '';
    }
}

/**
 * 转义HTML
 * @param {string} text 需要转义的文本
 * @returns {string} 转义后的文本
 */
function escapeHtml(text) {
    if (!text) return '';
    
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    
    return text.toString().replace(/[&<>"']/g, m => map[m]);
}